package de.hub.sar.itsec.sslfetcher.saver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.security.provider.X509Factory;

public class CertSaver implements ISaver {
	private final String path;
	private final String ext;
	
	public CertSaver(final String path, final String ext) {
		File file;
		
		this.ext = ext;
		
		if (!path.isEmpty() && !path.endsWith(File.separator)) {
			this.path = path + File.separatorChar;
		} else {
			this.path = path;
		}
		
		file = new File(this.path);
		if (!file.exists() && !file.mkdirs()) {
			// TODO
		}
	}
	
	@Override
	public synchronized boolean save(final String name, final byte[] cert) {
		FileOutputStream out;
		
		try {
			out = new FileOutputStream(this.path + name + this.ext);
			out.write(X509Factory.BEGIN_CERT.getBytes());
			out.write('\n');
			out.write(new sun.misc.BASE64Encoder().encode(cert).getBytes());
			out.write('\n');
			out.write(X509Factory.END_CERT.getBytes());
			out.write('\n');
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		}
		
		return true;
	}
}
